package com.czmh.etc.interpreter.Utils;

import com.czmh.etc.interpreter.entity.base.InterpreterContent;

import java.io.UnsupportedEncodingException;

/**
 * Created by Huangyk on 2019/6/6.
 */
public class StringUtils {
    public final static int PAD_DIRECTION_LEFT = 1;
    public final static int PAD_DIRECTION_RIGHT = 2;

    public static String rightPadByByte(String str, char padChar){
        return (str + padChar);
    }

    public static String leftPadByByte(String str, char padChar){
        return (padChar + str);
    }

    public static String padByByteLen(String str, char padChar, int padDirection){
        switch (padDirection){
            case StringUtils.PAD_DIRECTION_LEFT:
                str = StringUtils.leftPadByByte(str, padChar);
                break;
            case StringUtils.PAD_DIRECTION_RIGHT:
                str = StringUtils.rightPadByByte(str, padChar);
                break;
        }

        return str;
    }

    public static String rightPadByByteLen(String str, int size, char padChar) throws UnsupportedEncodingException {
        return padByByteLen(str, size, padChar, StringUtils.PAD_DIRECTION_RIGHT);
    }

    public static String leftPadByByteLen(String str, int size, char padChar) throws UnsupportedEncodingException {
        return padByByteLen(str, size, padChar, StringUtils.PAD_DIRECTION_LEFT);
    }

    public static String padByByteLen(String str, int size, char padChar, int padDirection) throws UnsupportedEncodingException {
        return padByByteLen(str, size, padChar, padDirection, InterpreterContent.CHARACTER_SET);
    }

    public static String padByByteLen(String str, int size, char padChar, int padDirection, String characterSet) throws UnsupportedEncodingException {
        if(str == null){
            return null;
        }else{
            try {
                byte[] strBytes = str.getBytes(characterSet);
                byte[] padBytes = new String(new char[]{padChar}).getBytes(characterSet);

                if(strBytes.length >= size){
                    return str;
                }else{
                    if((size - strBytes.length) % (padBytes.length) != 0){
                        throw new RuntimeException("padChar的字节长度与剩余长度不匹配！");
                    }else{
                        int times = (size - strBytes.length) / (padBytes.length);
                        for(int i = 0; i < times; i++){
                            str = padByByteLen(str, padChar, padDirection);
                        }
                    }
                }

                return str;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                throw e;
            }
        }
    }
}
